package RozetkaPages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import util.PropertyLoader;


import java.util.concurrent.TimeUnit;


/**
 * Created by Yulia on 31.03.14.
 */
public abstract class BasePage {

    protected WebDriver driver;
    protected String pageUrl;
    protected String websiteUrl;

    private By searchField = By.className("header-search-input-text");
    private By buttonSearch = By.cssSelector(".btn-link-i");
    private By authorizationPopup = By.cssSelector(".m-user-link.xhr");
    private By userField = By.cssSelector("input[name='login']");
    private By passwordField = By.cssSelector("input[name='password']");
    private By buttonLoginSubmit = By.cssSelector(".auth-f-submit>button[type='submit']");
    private By userProfile = By.cssSelector("a[name='profile']");
    private By signOut = By.cssSelector("a[name='signout']");
    private By basketLink = By.name("open_cart");


    abstract public void open();

    public BasePage(WebDriver driver, String pageUrl)
    {
        websiteUrl = PropertyLoader.loadProperty("site.url");
        this.pageUrl = websiteUrl + pageUrl;
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public boolean isOpened()
    {
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        return driver.getCurrentUrl().contains(pageUrl);
    }

    public String getPageUrl()
    {
        return pageUrl;
    }

    public void clickOnMenuItem(String tabSelector)
    {
        driver.findElement(By.cssSelector(tabSelector)).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    public void search(String productTitle)
    {
        driver.findElement(searchField).sendKeys(productTitle);
        driver.findElement(buttonSearch).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    public void openAuthorizationPopUp()
    {
        driver.findElement(authorizationPopup).click();
    }

    public void login(String email, String password)
    {
        driver.findElement(userField).clear();
        driver.findElement(userField).sendKeys(email);

        driver.findElement(passwordField).clear();
        driver.findElement(passwordField).sendKeys(password);

        driver.findElement(buttonLoginSubmit).click();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.DAYS);
    }

    public void isLoggedIn()
    {
        driver.findElement(userProfile).isDisplayed();
    }

    public void logout()
    {
        driver.findElement(signOut).click();
    }

    public void openBasket()
    {
        driver.findElement(basketLink).click();
    }
}
